package com.bjxst.commons;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;

/*jdbc工具类  获取connection对象
* 在工具类的方法都是静态方法*/
public class JdbcUtils {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    static {
        try {
        //db.properties 文件    getBundle("db")  db是不要扩展名
        ResourceBundle bundle = ResourceBundle.getBundle("db");
        //从文件中获得数据
           // url = bundle.getString("url");
        driver = bundle.getString("driver");
        url = bundle.getString("url");
        username = bundle.getString("username");
        password = bundle.getString("pwd");
        //加载数据库驱动
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //获取连接方法   返回Connection对象
    public static Connection getConnection(){
         Connection conn = null;
        try{
            conn = DriverManager.getConnection(url,username,password);
        }catch (Exception e){
            e.printStackTrace();
        }
        return conn;
    }

    //关闭连接方法
    public static void closeConnection(Connection conn){
        try{
            conn.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //事务回滚
    public static void rollbackConnection(Connection conn){
        try {
            conn.rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
